package com.lottery.im.module.tim.message;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.lottery.im.MyApplication;
import com.lottery.im.R;
import com.lottery.im.constant.SpKeyConstant;
import com.lottery.im.module.chat.adapter.ChatAdapter;
import com.lottery.im.module.tim.utils.MediaUtil;
import com.lottery.im.module.tim.utils.TimFileUtil;
import com.lottery.im.util.SPUtils;
import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMGroupMemberInfo;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMSoundElem;
import java.io.File;
import java.io.FileInputStream;

/**
 * 语音消息数据
 */
public class VoiceMessage extends Message {

  private static final String TAG = "VoiceMessage";

  public VoiceMessage(TIMMessage message) {
    this.message = message;
  }

  /**
   * 语音消息构造方法
   *
   * @param duration 时长
   * @param filePath 语音数据地址
   */
  public VoiceMessage(long duration, String filePath) {
    message = new TIMMessage();
    TIMSoundElem elem = new TIMSoundElem();
    elem.setPath(filePath);
    elem.setDuration(duration);  //填写语音时长
    message.addElement(elem);
  }

  /**
   * 显示消息
   *
   * @param viewHolder 界面样式
   * @param context 显示消息的上下文
   */
  @Override
  public void showMessage(ChatAdapter.ViewHolder viewHolder, Context context) {
    if (checkRevoke(viewHolder)) return;

    LinearLayout linearLayout;

    if (message.isSelf()) {
      linearLayout = (LinearLayout) LayoutInflater.from(MyApplication.getInstance())
          .inflate(R.layout.layout_message_voice_right, null);
    } else {
      linearLayout = (LinearLayout) LayoutInflater.from(MyApplication.getInstance())
          .inflate(R.layout.layout_message_voice_left, null);
    }

    ImageView voiceIcon = linearLayout.findViewById(R.id.voiceIcon);
    TextView tv = linearLayout.findViewById(R.id.voiceText);

    final AnimationDrawable frameAnimatio = (AnimationDrawable) voiceIcon.getBackground();

    tv.setText(String.valueOf(((TIMSoundElem) message.getElement(0)).getDuration()) + "’");

    clearView(viewHolder);
    getBubbleView(viewHolder).addView(linearLayout);
    getBubbleView(viewHolder).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        VoiceMessage.this.playAudio(frameAnimatio);
      }
    });
    showStatus(viewHolder);
  }

  /**
   * 获取消息摘要
   */
  @Override
  public String getSummary() {
    String str = getRevokeSummary();
    if (str != null) return str;
    StringBuilder result = new StringBuilder();

    TIMGroupMemberInfo senderGroupMemberProfile = message.getSenderGroupMemberProfile();
    if (null != senderGroupMemberProfile) {
      // 说明这是群聊消息
      if (TextUtils.isEmpty(message.getSenderGroupMemberProfile().getNameCard())) {
        // 有自己的群名片
        result.append(message.getSenderProfile().getNickName() + "：");
      } else {
        // 无自己的群名片
        result.append(message.getSenderGroupMemberProfile().getNameCard() + "：");
      }
    }
    result.append(MyApplication.getInstance().getString(R.string.summary_voice));
    return result.toString();
  }

  /**
   * 保存消息或消息文件
   */
  @Override
  public void save() {

  }

  private void playAudio(final AnimationDrawable frameAnimatio) {
    boolean isPhone =
        (boolean) SPUtils.get(MyApplication.getInstance(), SpKeyConstant.SPEAKERPHONE_KEY, false);
    AudioManager audioManager =
        (AudioManager) MyApplication.getInstance().getSystemService(Context.AUDIO_SERVICE);
    if (isPhone) {
      audioManager.setSpeakerphoneOn(false);
      audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
    } else {
      audioManager.setMode(AudioManager.MODE_NORMAL);
      audioManager.setSpeakerphoneOn(true);
    }
    MediaUtil.getInstance().setAudioStreamType(isPhone);
    TIMSoundElem elem = (TIMSoundElem) message.getElement(0);
    final File tempAudio = TimFileUtil.getTempFile(TimFileUtil.FileType.AUDIO);
    elem.getSoundToFile(tempAudio.getAbsolutePath(), new TIMCallBack() {
      @Override
      public void onError(int i, String s) {

      }

      @Override
      public void onSuccess() {
        try {
          FileInputStream fis = new FileInputStream(tempAudio);
          MediaUtil.getInstance().play(fis);
          frameAnimatio.start();
          MediaUtil.getInstance().setEventListener(new MediaUtil.EventListener() {
            @Override
            public void onStop() {
              frameAnimatio.stop();
              frameAnimatio.selectDrawable(0);
            }
          });
        } catch (Exception e) {

        }
      }
    });
  }
}